package com.mcptt.http.operator;

import com.cloudptt.api.product.log.Log;
import com.mcptt.http.operator.file.OnUploadListener;
import com.mcptt.http.operator.file.ProgressRequestBody;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Map;

import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class OkHttpUtils {
	private static final String THIS_FILE = "OkHttpUtils";
	private static OkHttpUtils okHttpUtils = null;

	public static OkHttpUtils getInstance() {
		if (okHttpUtils == null) {
			synchronized (OkHttpUtils.class) {
				if (okHttpUtils == null) {
					okHttpUtils = new OkHttpUtils();
				}
			}

		}
		return okHttpUtils;
	}

	private static OkHttpClient okHttpClient = null;

	private synchronized static OkHttpClient getOkHttpClient() {
		if (okHttpClient == null) {
			//            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
			//                @Override
			//                public void log(String message) {
			//                    Log.i("拦截器", message);
			//                }
			//            });
			// 
			//            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);


			okHttpClient = new OkHttpClient.Builder().build();

		}
		return okHttpClient;
	}


	//get方法
	public void doGet(String url, Callback callback) {

		OkHttpClient okHttpClient = getOkHttpClient();

		Request request = new Request.Builder()
				.url(url)
				.build();

		okHttpClient.newCall(request).enqueue(callback);
	}

	//doPost方法
	public void doGet(String url, Map<String, String> params, Callback callback) {

		OkHttpClient okHttpClient = getOkHttpClient();
		try {
			MediaType JSON = MediaType.parse("application/json; charset=utf-8");
			JSONObject json = new JSONObject();
			FormBody.Builder builder = new FormBody.Builder();
			for (String key : params.keySet()) {
				builder.add(key, params.get(key));

				json.put(key, params.get(key));

			}
			Log.d(THIS_FILE, "doGetJson url = " + url + " json = " + json );
			RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
			Request request = new Request.Builder()
					.url(url)
					.get()
					.put(requestBody)
					.build();

			okHttpClient.newCall(request).enqueue(callback);

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}



	}

	//doPost方法
	public void doPutJson(String url, Map<String, String> params, Callback callback) {

		OkHttpClient okHttpClient = getOkHttpClient();
		try {
			MediaType JSON = MediaType.parse("application/json; charset=utf-8");
			JSONObject json = new JSONObject();
			FormBody.Builder builder = new FormBody.Builder();
			for (String key : params.keySet()) {
				builder.add(key, params.get(key));

				json.put(key, params.get(key));

			}
			Log.d(THIS_FILE, "doPutJson url = " + url + " json = " + json );
			RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
			Request request = new Request.Builder()
                    .url(url)
                    .put(requestBody)
                    .build();

			okHttpClient.newCall(request).enqueue(callback);

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			Log.d(THIS_FILE, "doPutJson JSONException e = " + e );
			e.printStackTrace();
		}
		catch (Exception e)
		{
			Log.d(THIS_FILE, "doPutJson Exception e = " + e );
			e.printStackTrace();
		}



	}

	public void doPostFile(String url,File file, long len, Callback callback,OnUploadListener listener,String num) {
		Log.d(THIS_FILE, "doPostFile url = " + url + " file = " + file + " num = " +  num);
		
		MultipartBody.Builder builder = new MultipartBody.Builder();
		
		JSONObject json = new JSONObject();
		try
		{
		json.put("UserID", num);
		json.put("FileName", file.getName());
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
//		builder.setType(MultipartBody.FORM);
		
		builder.addPart(RequestBody.create(MediaType.parse("application/json"),json.toString()));
//		builder.addFormDataPart("","",RequestBody.create(MediaType.parse("application/json"),json.toString()));
//		//第一个参数要与Servlet中的一致
		builder.addFormDataPart("file",file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"),file));

		MultipartBody multipartBody = builder.build();
		String remoteFilePath = url + file.getName();
		Request request = new Request.Builder().url(url).post(new ProgressRequestBody(multipartBody,listener,remoteFilePath,len)).build();
		Log.d(THIS_FILE, "doPostFile request = " + request);
		okHttpClient.newCall(request).enqueue(callback);

	}

	public void doPostFile(String url,File file, Callback callback,OnUploadListener listener) {
		Log.d(THIS_FILE, "doPostFile url = " + url + " file = " + file );

//		try {
//			HttpClient client = new HttpClient();
//			PostMethod post = new PostMethod(url);
//			Part[] parts = { new FilePart("logFile", file), new StringPart("logType", "0") };
//			post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
//			client.executeMethod(post);
//		}
//		catch (Exception e)
//		{
//
//		}

		MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

//		JSONObject json = new JSONObject();
//		try
//		{
//			json.put("logFile", file.getName());
//			json.put("logType", 0);
//		}
//		catch(Exception e)
//		{
//			e.printStackTrace();
//		}

//		builder.setType(MultipartBody.FORM);

		//builder.addFormDataPart("logType", "0");//.addPart(RequestBody.create(MediaType.parse("application/json"),json.toString()));
		//builder.addFormDataPart("logType",RequestBody.create(MediaType.parse("text/plain"),"0").toString());
		//builder.addFormDataPart("userphone", userPhone);
		builder.addFormDataPart("logType","0");
		//builder.addFormDataPart("logType","0",RequestBody.create(MediaType.parse("text/plain"),"0"));
		builder.addFormDataPart("logFile",file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"),file));
//		//第一个参数要与Servlet中的一致                            RequestBody.create(MEDIA_TYPE_MARKDOWN, file)
		//MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
		//builder.addFormDataPart("logFile",file.getName(), null);

		MultipartBody multipartBody = builder.build();
		String remoteFilePath = url + file.getName();
		Request request = new Request.Builder().url(url).post(new ProgressRequestBody(multipartBody,listener,remoteFilePath,file.length())).build();
		Log.d(THIS_FILE, "doPostFile request = " + request);
		okHttpClient.newCall(request).enqueue(callback);

	}

	public void download(final String url, String jsonStr, Callback callback) {
		Log.d(THIS_FILE, "download url = " + url + " jsonStr = " + jsonStr );
		MediaType JSON = MediaType.parse("application/json; charset=utf-8");
		RequestBody requestBody = RequestBody.create(JSON, String.valueOf(jsonStr));
		Request request = new Request.Builder()
                .url(url)
                .put(requestBody)
                .build();
		//异步请求
		okHttpClient.newCall(request).enqueue(callback);
	}
}